package com.tsl.reggie.controller;

import com.tsl.reggie.common.R;
import com.tsl.reggie.utils.AliOSSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {
    //获取根路径
    @Value(value = "${reggie.basePath}")
    private String basePath;
    @Autowired
    AliOSSUtils aliOSSUtils;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        /*//获取文件原始名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //判断basePath是否存在,不存在就创建一个
        File dir = new File(basePath);
        if (!dir.exists()){
            dir.mkdirs();
        }
        String filename = UUID.randomUUID()+suffix;
        //将file另存为filename
        file.transferTo(new File(basePath + filename));*/
        String filename = aliOSSUtils.upload(file);

        return R.success(filename);
    }

    @GetMapping("download")
    public void download(@RequestParam(name = "name") String filename, HttpServletResponse response) throws Exception {
        aliOSSUtils.downLoad(filename,response);
    }
}
